#coding=utf-8
#LightCam SSH抓数据程序测试版
#init by hfh 20150724

import multiprocessing,subprocess,sys
import socket,os,time,re,traceback,json,binascii
import lc_libs,pymongo


def oper(comd):
	try:
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		#判断子进程是否结束
		timeflag=0
		while True:
			if popen.poll()==None:
				time.sleep(0.1)
				timeflag=timeflag+1
				if timeflag > 100:
					return "TimeOut"
				else:
					continue
			else:
				break
		line=popen.stdout.read()
		
		res=json.loads(line)
		
		res['rows']=sorted(res['rows'],key=lambda d:[d['Source'],d['Target'][0],int(d['Target'].replace('front','').replace('mdkernel',''))],reverse=False)
		file=open(lchome+"/pyweb/static/json/ipsla/ipsla.json",'w')
		file.write(json.dumps(res))
		file.close()
		
		for items in res['rows']:
			Source=items['Source']
			Target=items['Target']
			Rtt=items['Rtt']
			Loss=items['Loss']
			Time=items['Time']
			saveData(Source,Target,Rtt,Loss,Time)
	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()


def saveData(devicename,Target,Rtt,Loss,Time):
	expr={'Source':devicename,'Target':Target}
	datas={'Source':devicename,'Target':Target,'Rtt':str(Rtt),'Loss':Loss,'Time':Time}
	sortcont=[("Source",pymongo.ASCENDING),("Target",pymongo.ASCENDING)]
	opts=db.queryData(ipsla_table,expr,sortcont,0)
	res=db.genResult(opts)
	if len(res)==0:db.insertDatas(ipsla_table,datas)
	else:db.updateData(ipsla_table,expr,datas)
	
if __name__ == "__main__":
	
	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()

	agent_hostname=lc_libs.lc_gethostname()

	#初始化数据库
	
	db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

	db.connect()
	Conn=db.getConn()
	if Conn==None:
		print "Can not Connect to the MondbDB"
		exit(0)
	
	events_dbname='lc_events'
	ipsla_tablename='lc_ipsla'
	
	history_dbname='lc_history'
	history_tablename="lc_basic"
		
	events_db=db.useDatabase(events_dbname)
	ipsla_table=db.UseCollection(events_db,ipsla_tablename)
		
	history_db=db.useDatabase(history_dbname)
	history_table=db.UseCollection(history_db,history_tablename)
	
	while True:
		try:
			comd='ssh ywn_monitor1 "source ~/.bash_profile;cd /monitor/LightCam/scripts/;LightCamPy lc_query.py lc_events lc_ipsla"'
			oper(comd)
			time.sleep(60)
		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" \n"+excinfo+"\n")
			logfile.flush()
			time.sleep(10)
			continue
		
		
